{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 1、关于对话模型中消息（message）的使用\n",
    "\n",
    "标准的对话模型的调用过程：\n",
    "\n",
    "invoke()的输入可以是多种类型，典型的类型有：① 字符串类型 ② 消息列表\n",
    "\n",
    "invoke()的输出类型：BaseMessage的子类：AIMessage"
   ],
   "id": "f4b92bc3feb5348e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:01:19.062155Z",
     "start_time": "2025-09-27T21:01:13.988462Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "from langchain_openai import ChatOpenAI\n",
    "import os\n",
    "\n",
    "import dotenv\n",
    "\n",
    "# 前提：加载配置文件\n",
    "dotenv.load_dotenv()\n",
    "os.environ[\"OPENAI_API_KEY\"]=os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ[\"OPENAI_BASE_URL\"]=os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "# 1、获取对话模型\n",
    "chat_model = ChatOpenAI(\n",
    "    model=\"gpt-4o-mini\"\n",
    ")\n",
    "\n",
    "# 2、调用对话模型\n",
    "response = chat_model.invoke(\"帮我解释一下什么是langchain?\")\n",
    "\n",
    "# 3、处理响应数据\n",
    "# print(response)\n",
    "print(response.content)\n",
    "print(type(response))  #<class 'langchain_core.messages.ai.AIMessage'>"
   ],
   "id": "6a7cddebb12dbe8",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/miniconda3/envs/pyth310/lib/python3.10/site-packages/requests/__init__.py:86: RequestsDependencyWarning: Unable to find acceptable character detection dependency (chardet or charset_normalizer).\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LangChain 是一个用于构建基于语言模型的应用程序的框架，它使得开发者能更轻松地与各种语言模型（如 GPT-3、GPT-4、以及其他的语言生成和理解模型）进行交互。LangChain 提供了多种模块和组件，帮助开发者实现自然语言处理（NLP）相关的功能，比如文本生成、对话管理、知识问答等。\n",
      "\n",
      "主要特点包括：\n",
      "\n",
      "1. **组件化设计**：LangChain 将系统的构建分解为多个可以独立使用的组件，例如文档加载、文本处理、问答系统、记忆管理等。\n",
      "\n",
      "2. **与外部数据源的集成**：LangChain 可以轻松地集成到现有的数据源中，使得语言模型能够访问和利用这些数据，这对于构建有深度背景知识的应用程序尤为重要。\n",
      "\n",
      "3. **状态管理**：它支持复杂的对话状态管理，使得能够创建更具上下文意识的对话系统。\n",
      "\n",
      "4. **可扩展性**：开发者可以根据自己的需要扩展和定制 LangChain 的功能，以适应特定的应用场景。\n",
      "\n",
      "5. **交互式应用**：支持与用户的实时交互，使得应用程序更具互动性。\n",
      "\n",
      "LangChain 适用于多种应用场景，包括聊天机器人、推荐系统、内容生成、信息检索等，旨在加速开发过程，提高开发者的生产力。\n",
      "<class 'langchain_core.messages.ai.AIMessage'>\n"
     ]
    }
   ],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "关于消息：\n",
    "\n",
    "有典型的三类消息：SystemMessage \\ HumanMessage \\ AIMessage\n",
    "\n",
    "举例1：\n"
   ],
   "id": "56629d85e07d4d52"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:05:14.034252Z",
     "start_time": "2025-09-27T21:05:14.028908Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "\n",
    "system_message = SystemMessage(content=\"你是一个英语教学方向的专家\")\n",
    "human_message = HumanMessage(content=\"帮我制定一个英语六级学习的计划\")\n",
    "\n",
    "messages = [system_message,human_message]\n",
    "\n",
    "print(messages)"
   ],
   "id": "efc2c9e86cb0c2a6",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[SystemMessage(content='你是一个英语教学方向的专家', additional_kwargs={}, response_metadata={}), HumanMessage(content='帮我制定一个英语六级学习的计划', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "使用大模型，调用消息列表",
   "id": "fe80628b5b5bae52"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:06:05.509875Z",
     "start_time": "2025-09-27T21:05:58.614116Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = chat_model.invoke(messages)\n",
    "\n",
    "print(type(response))\n",
    "print(response.content)"
   ],
   "id": "b0eec94f79ff3c96",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'langchain_core.messages.ai.AIMessage'>\n",
      "当然可以！以下是一个为期三个月的英语六级学习计划，分为每周的学习目标和内容，帮助你逐步提升英语水平，最终通过六级考试。\n",
      "\n",
      "### 学习计划概述\n",
      "- **目标**：提高英语听、说、读、写能力，准备六级考试\n",
      "- **时长**：3个月（12周）\n",
      "- **每周学习时间**：根据个人情况，建议每天2-3小时\n",
      "\n",
      "### 第一周：基础评估与学习材料准备\n",
      "- **目标**：评估自己当前的英语水平，收集学习材料\n",
      "- **内容**：\n",
      "  - 完成一份六级模拟测试，了解自己的薄弱环节\n",
      "  - 收集六级核心词汇书、真题、听力资料等\n",
      "  - 制定每天的固定学习时间表\n",
      "\n",
      "### 第二周：词汇与语法日常\n",
      "- **目标**：建立扎实的词汇基础\n",
      "- **内容**：\n",
      "  - 学习300个六级高频词汇\n",
      "  - 每天背诵并使用这些词汇造句\n",
      "  - 复习基础语法知识，特别是时态和从句\n",
      "\n",
      "### 第三周：听力训练\n",
      "- **目标**：提高听力理解能力\n",
      "- **内容**：\n",
      "  - 每天听30分钟六级听力练习\n",
      "  - 选择TED演讲、英语新闻等多样化素材\n",
      "  - 做听力笔记，理解大意\n",
      "\n",
      "### 第四周：阅读理解\n",
      "- **目标**：提高阅读速度与理解能力\n",
      "- **内容**：\n",
      "  - 每天阅读一篇六级真题阅读理解\n",
      "  - 记录生词，加强上下文理解\n",
      "  - 练习速读技巧\n",
      "\n",
      "### 第五周：写作与翻译\n",
      "- **目标**：提升写作能力\n",
      "- **内容**：\n",
      "  - 每周写一篇六级作文，主题从真题中选择\n",
      "  - 学习常用的写作模板和句式\n",
      "  - 翻译每周一篇中英互译的经典短文\n",
      "\n",
      "### 第六周：口语练习\n",
      "- **目标**：提高口语表达能力\n",
      "- **内容**：\n",
      "  - 每天进行15-30分钟的口语练习\n",
      "  - 找语言伙伴或使用口语学习App\n",
      "  - 进行模拟口语考试，练习常见话题\n",
      "\n",
      "### 第七周：综合复习与反馈\n",
      "- **目标**：查漏补缺，巩固知识\n",
      "- **内容**：\n",
      "  - 综合前6周学习的词汇、语法、听力、阅读、写作\n",
      "  - 定期查找老师或同学的反馈\n",
      "  - 参加模拟考试，检验学习成效\n",
      "\n",
      "### 第八周：专项训练\n",
      "- **目标**：针对薄弱项进行强化训练\n",
      "- **内容**：\n",
      "  - 分析模拟考试错题，找出知识盲点\n",
      "  - 针对薄弱环节（如听力或写作）进行深入学习\n",
      "  - 做专项练习题\n",
      "\n",
      "### 第九周：真题练习与时间管理\n",
      "- **目标**：模拟真实考试环境\n",
      "- **内容**：\n",
      "  - 每周完成两套六级真题（听力+阅读+写作）\n",
      "  - 练习时间管理，模拟正式考试\n",
      "  - 记录并分析错误，查漏补缺\n",
      "\n",
      "### 第十周：知识巩固与口语实践\n",
      "- **目标**：稳固基础，提升自信\n",
      "- **内容**：\n",
      "  - 复习所有词汇，特别是难记的词\n",
      "  - 参与英语角或讨论小组，提高口语流利度\n",
      "  - 模拟真实场景，练习口语表达\n",
      "\n",
      "### 第十一周：模拟考试\n",
      "- **目标**：适应考试氛围\n",
      "- **内容**：\n",
      "  - 参加完整的模拟考试\n",
      "  - 根据结果调整最后冲刺计划\n",
      "  - 休息并保持心理放松\n",
      "\n",
      "### 第十二周：最后冲刺\n",
      "- **目标**：提升信心，巩固重点\n",
      "- **内容**：\n",
      "  - 复习所有重要内容和错题\n",
      "  - 保持良好的作息，确保充足的睡眠\n",
      "  - 考试前进行放松活动，保持放松心态\n",
      "\n",
      "### 附加建议\n",
      "- 定期与老师或其他同学进行交流，互相鼓励和监督。\n",
      "- 使用手机应用程序（如Anki, Quizlet）帮助记忆单词。\n",
      "- 保持积极的学习态度，及时调整学习计划以适应自己的进步与困难。\n",
      "\n",
      "希望这个计划能帮助你顺利通过英语六级考试！如果有其他问题或具体需求，欢迎随时询问。\n"
     ]
    }
   ],
   "execution_count": 5
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "4a7663904d1ef2b5"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:10:07.498405Z",
     "start_time": "2025-09-27T21:10:07.492239Z"
    }
   },
   "cell_type": "code",
   "source": [
    "system_message = SystemMessage(\n",
    "    content=\"你是一个英语教学方向的专家\",\n",
    "    additional_kwargs={\"tool\":\"invoke_func1\"}\n",
    "                               )\n",
    "human_message = HumanMessage(content=\"帮我制定一个英语六级学习的计划\")\n",
    "messages = [system_message,human_message]\n",
    "\n",
    "print(messages)"
   ],
   "id": "2e0d5370ad11406e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[SystemMessage(content='你是一个英语教学方向的专家', additional_kwargs={'tool': 'invoke_func1'}, response_metadata={}), HumanMessage(content='帮我制定一个英语六级学习的计划', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例3:ChatMessage平时我们使用的不多，了解一下即可",
   "id": "af1a742e52c94d3b"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:13:16.166046Z",
     "start_time": "2025-09-27T21:13:16.159798Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import AIMessage, ChatMessage\n",
    "\n",
    "# 创建不同类型的消息\n",
    "system_message = SystemMessage(content=\"你是一个专业的数据科学家\")\n",
    "human_message = HumanMessage(content=\"解释一下随机森林算法\")\n",
    "ai_message = AIMessage(content=\"随机森林是一种集成学习方法...\")\n",
    "custom_message = ChatMessage(role=\"analyst\",content=\"补充一点关于超参数调优的信息\")\n",
    "\n",
    "print(system_message.content)\n",
    "print(human_message.content)\n",
    "print(ai_message.content)\n",
    "print(custom_message.content)"
   ],
   "id": "2368e965eb7f99fc",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你是一个专业的数据科学家\n",
      "解释一下随机森林算法\n",
      "随机森林是一种集成学习方法...\n",
      "补充一点关于超参数调优的信息\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 2、关于多轮对话与上下文记忆\n",
    "\n",
    "前提："
   ],
   "id": "157276e025c31c2b"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:14:11.432645Z",
     "start_time": "2025-09-27T21:14:11.424417Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import dotenv\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "chat_model = ChatOpenAI(\n",
    "\tmodel=\"gpt-4o-mini\"\n",
    ")"
   ],
   "id": "af42be4b2d80cf82",
   "outputs": [],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "测试1：大模型本身是没有上下文记忆能力的",
   "id": "6ca7c34573fef4c0"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:15:31.039847Z",
     "start_time": "2025-09-27T21:15:29.040776Z"
    }
   },
   "cell_type": "code",
   "source": [
    "system_messgae = SystemMessage(content=\"我是一个人工智能的助手，我的名字叫小智\")\n",
    "human_message = HumanMessage(content=\"猫王是一只猫吗？\")\n",
    "\n",
    "messages = [system_message,human_message]\n",
    "\n",
    "#调用大模型，传入messages\n",
    "response = chat_model.invoke(messages)\n",
    "# print(response.content)\n",
    "\n",
    "response1 = chat_model.invoke(\"你叫什么名字？\")\n",
    "print(response1.content)"
   ],
   "id": "6c4d39ede5e8032a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "“猫王”通常是指美国著名的音乐家埃尔维斯·普雷斯利（Elvis Presley），他以“猫王”（King of Rock and Roll）这个称号而闻名。因此，猫王并不是指一只真实的猫，而是一个代表文化和音乐的符号。如果你指的是其他含义，请提供更多背景信息。\n",
      "我是一个人工智能助手，没有具体的名字。你可以叫我助手或者AI。如果你有任何问题，随时可以问我！\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "测试2：",
   "id": "237b0fb55fc68f50"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:16:09.336260Z",
     "start_time": "2025-09-27T21:16:08.365078Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "\n",
    "sys_message = SystemMessage(\n",
    "    content=\"我是一个人工智能的助手，我的名字叫小智\",\n",
    ")\n",
    "human_message = HumanMessage(content=\"猫王是一只猫吗？\")\n",
    "human_message1 = HumanMessage(content=\"你叫什么名字？\")\n",
    "\n",
    "messages = [sys_message, human_message,human_message1]\n",
    "\n",
    "#调用大模型，传入messages\n",
    "response = chat_model.invoke(messages)\n",
    "print(response.content)"
   ],
   "id": "63ba00e8437e42f1",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我叫小智。你有什么问题或需要帮助的吗？\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "测试3：",
   "id": "fdb5485f5a09ee03"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:16:44.066439Z",
     "start_time": "2025-09-27T21:16:43.277307Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "\n",
    "sys_message = SystemMessage(\n",
    "    content=\"我是一个人工智能的助手，我的名字叫小智\",\n",
    ")\n",
    "human_message = HumanMessage(content=\"猫王是一只猫吗？\")\n",
    "\n",
    "sys_message1 = SystemMessage(\n",
    "    content=\"我可以做很多事情，有需要就找我吧\",\n",
    ")\n",
    "\n",
    "human_message1 = HumanMessage(content=\"你叫什么名字？\")\n",
    "\n",
    "messages = [sys_message, human_message,sys_message1,human_message1]\n",
    "\n",
    "#调用大模型，传入messages\n",
    "response = chat_model.invoke(messages)\n",
    "print(response.content)"
   ],
   "id": "10148616dc95282f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我叫小智，很高兴认识你！有什么我可以帮助你的吗？\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "测试4：",
   "id": "c353b781b0024a9c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:17:26.538906Z",
     "start_time": "2025-09-27T21:17:23.891580Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "\n",
    "# 第1组\n",
    "sys_message = SystemMessage(\n",
    "    content=\"我是一个人工智能的助手，我的名字叫小智\",\n",
    ")\n",
    "human_message = HumanMessage(content=\"猫王是一只猫吗？\")\n",
    "\n",
    "messages = [sys_message, human_message]\n",
    "\n",
    "# 第2组\n",
    "sys_message1 = SystemMessage(\n",
    "    content=\"我可以做很多事情，有需要就找我吧\",\n",
    ")\n",
    "\n",
    "human_message1 = HumanMessage(content=\"你叫什么名字？\")\n",
    "\n",
    "messages1 = [sys_message1,human_message1]\n",
    "\n",
    "#调用大模型，传入messages\n",
    "response = chat_model.invoke(messages)\n",
    "# print(response.content)\n",
    "\n",
    "response = chat_model.invoke(messages1)\n",
    "print(response.content)"
   ],
   "id": "21088c7a7884e3f9",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我是一个人工智能助手，没有具体的名字。你可以叫我助手或者任何你喜欢的名字！有什么我可以帮助你的吗？\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "测试5：",
   "id": "d49eebae1012"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:18:48.489026Z",
     "start_time": "2025-09-27T21:18:47.649312Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage, AIMessage\n",
    "\n",
    "messages = [\n",
    "    SystemMessage(content=\"我是一个人工智能助手，我的名字叫小智\"),\n",
    "    HumanMessage(content=\"人工智能英文怎么说？\"),\n",
    "    AIMessage(content=\"AI\"),\n",
    "    HumanMessage(content=\"你叫什么名字\"),\n",
    "]\n",
    "\n",
    "messages1 = [\n",
    "    SystemMessage(content=\"我是一个人工智能助手，我的名字叫小智\"),\n",
    "    HumanMessage(content=\"很高兴认识你\"),\n",
    "    AIMessage(content=\"我也很高兴认识你\"),\n",
    "    HumanMessage(content=\"你叫什么名字\"),\n",
    "]\n",
    "\n",
    "messages2 = [\n",
    "    SystemMessage(content=\"我是一个人工智能助手，我的名字叫小智\"),\n",
    "    HumanMessage(content=\"人工智能英文怎么说？\"),\n",
    "    AIMessage(content=\"AI\"),\n",
    "    HumanMessage(content=\"你叫什么名字\"),\n",
    "]\n",
    "\n",
    "# chat_model.invoke(messages)\n",
    "# chat_model.invoke(messages1)\n",
    "chat_model.invoke(messages2)"
   ],
   "id": "efe98b98e0c60d33",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='我叫小智。你有什么问题或需要帮助的地方吗？', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 16, 'prompt_tokens': 40, 'total_tokens': 56, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-CKWbYKqO7CMvBaTs5C05jLsXFgcWo', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--0f4fbd6f-ff03-4b6d-8239-30780ec2e6c4-0', usage_metadata={'input_tokens': 40, 'output_tokens': 16, 'total_tokens': 56, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 3、关于模型调用的方法的说明\n",
    "\n",
    "invoke() / stream()\n",
    "\n",
    "batch():批量的调用\n",
    "\n",
    "ainvoke() / astream() / abatch():异步方法的调用\n",
    "\n",
    "举例1：体会invoke()阻塞式的调用"
   ],
   "id": "5d75eb55e275851a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:19:37.478843Z",
     "start_time": "2025-09-27T21:19:35.909932Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import dotenv\n",
    "from langchain_core.messages import HumanMessage\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "#初始化大模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 创建消息\n",
    "messages = [HumanMessage(content=\"你好，请介绍一下自己\")]\n",
    "\n",
    "# 非流式调用LLM获取响应\n",
    "response = chat_model.invoke(messages)\n",
    "\n",
    "# 打印响应内容\n",
    "print(response)"
   ],
   "id": "267395aec1fc34f3",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='你好！我是一个人工智能助手，旨在提供信息和帮助解决问题。我可以回答问题、提供建议、进行对话以及协助处理各种任务。我的知识覆盖了多个领域，包括科学、技术、文化、历史等。如果你有任何具体的问题或者需要帮助的地方，请随时告诉我！' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 67, 'prompt_tokens': 12, 'total_tokens': 79, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-CKWcKPUtFm6H88MeYBdHfLN4LH5ld', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None} id='run--d39fae87-4315-4718-8dbb-902d2515c46b-0' usage_metadata={'input_tokens': 12, 'output_tokens': 67, 'total_tokens': 79, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}\n"
     ]
    }
   ],
   "execution_count": 16
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：流式的演示",
   "id": "d4f0df33c5a5ff13"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:25:32.754236Z",
     "start_time": "2025-09-27T21:25:31.882619Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import dotenv\n",
    "from langchain_core.messages import HumanMessage\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "# 初始化大模型\n",
    "chat_model = ChatOpenAI(\n",
    "    model=\"gpt-4o-mini\",\n",
    "    streaming = True # 启用流式输出\n",
    ")\n",
    "\n",
    "# 创建消息\n",
    "messages = [HumanMessage(content=\"你好，请介绍一下自己\")]\n",
    "\n",
    "# 流式调用LLM获取响应\n",
    "print(\"开始流式输出：\")\n",
    "for chunk in chat_model.stream(messages):\n",
    "    # 逐个打印内容块\n",
    "    print(chunk.content, end=\"\", flush=True) # 刷新缓冲区 (无换行符，缓冲区未刷新，内容可能不会立即显示)\n",
    "\n",
    "print(\"\\n流式输出结束\")"
   ],
   "id": "acf8a99c0c9de336",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始流式输出：\n",
      "你好！我是一个人工智能助手，旨在提供信息和解答各种问题。我可以帮助你获取知识、解决问题、提供建议、进行对话等。如果你有任何具体的问题或想了解的内容，请随时告诉我！\n",
      "流式输出结束\n"
     ]
    }
   ],
   "execution_count": 22
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例3：使用batch，测试批量调用",
   "id": "c2e9b6cd72294019"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:27:05.564562Z",
     "start_time": "2025-09-27T21:27:01.664782Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import dotenv\n",
    "from langchain_core.messages import HumanMessage, SystemMessage\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "# 初始化大模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "messages1 = [SystemMessage(content=\"你是一位乐于助人的智能小助手\"),\n",
    "             HumanMessage(content=\"请帮我介绍一下什么是机器学习\"), ]\n",
    "\n",
    "messages2 = [SystemMessage(content=\"你是一位乐于助人的智能小助手\"),\n",
    "             HumanMessage(content=\"请帮我介绍一下什么是AIGC\"), ]\n",
    "\n",
    "messages3 = [SystemMessage(content=\"你是一位乐于助人的智能小助手\"),\n",
    "             HumanMessage(content=\"请帮我介绍一下什么是大模型技术\"), ]\n",
    "\n",
    "messages = [messages1, messages2, messages3]\n",
    "\n",
    "# 调用batch\n",
    "response = chat_model.batch(messages)\n",
    "\n",
    "print(response)"
   ],
   "id": "96c5e536f76d585d",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[AIMessage(content='机器学习是人工智能（AI）的一个子领域，涉及计算机系统如何通过经验提高其特定任务的性能，而无需明确编程。它的核心思想是让计算机利用数据进行学习，从中识别模式和规律，以便在未知数据上进行预测或决策。\\n\\n机器学习可以分为几类，主要包括：\\n\\n1. **监督学习**：在这种类型中，算法从带标签的数据中学习，标签是输入数据所对应的正确输出。监督学习的目标是训练模型，使其能够对新的、未见过的数据进行预测。例如，分类任务（如垃圾邮件检测）和回归任务（如房价预测）都属于监督学习。\\n\\n2. **无监督学习**：无监督学习算法从没有标签的数据中学习，旨在发现数据中的结构或模式。常见方法包括聚类（如顾客细分）和降维（如主成分分析）。\\n\\n3. **半监督学习**：这种方法结合了监督学习和无监督学习，使用少量有标签的数据和大量无标签的数据。它的目标是在有标签的数据较少时，提高模型的学习效率和准确性。\\n\\n4. **强化学习**：强化学习关注于通过与环境的交互来学习策略。代理（Agent）通过尝试不同的动作获得反馈（奖励或惩罚），并根据这些反馈调整其行为，以最大化长期收益。\\n\\n机器学习的应用非常广泛，包括自然语言处理（例如语言翻译、语音识别）、计算机视觉（如人脸识别、物体检测）、推荐系统（如电影推荐、产品推荐）、金融预测、医疗诊断等领域。 随着数据量的增加和计算能力的提升，机器学习在各行业的应用持续增长。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 381, 'prompt_tokens': 30, 'total_tokens': 411, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-CKWjWR4oi0IO4vES2RpuQEthoOz2H', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--57de6692-ae48-4078-87c1-38afa15391db-0', usage_metadata={'input_tokens': 30, 'output_tokens': 381, 'total_tokens': 411, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}), AIMessage(content='AIGC是“人工智能生成内容”（Artificial Intelligence Generated Content）的缩写。它指的是利用人工智能技术，特别是深度学习和自然语言处理算法，生成各种类型的内容，包括文本、图像、音频和视频等。\\n\\n以下是AIGC的一些关键特点和应用：\\n\\n1. **内容生成**：AIGC可以用来自动生成文章、故事、诗歌、编程代码等文本内容。同时，它也能够生成图像、音乐和视频等其他形式的创意内容。\\n\\n2. **自然语言处理（NLP）**：利用NLP技术，AIGC能够理解和生成符合人类语言习惯的文本，这使得生成的内容更加自然流畅。\\n\\n3. **个性化和定制化**：AIGC可以根据用户的需求生成个性化的内容，比如为特定受众或市场定制的营销材料。\\n\\n4. **提高效率**：通过自动生成内容，AIGC能够大大提高内容创作的效率，减轻人类创作者的工作负担，让他们有更多时间专注于创造性和战略性任务。\\n\\n5. **应用广泛**：AIGC在很多领域都有应用，包括广告创意、新闻报道、社交媒体内容生成、教育和培训材料、游戏开发等。\\n\\n尽管AIGC技术发展迅速，但也带来了伦理和版权方面的挑战，例如生成内容的真实性、原创性以及如何防止误用等问题。因此，相关的法律和规范也在不断发展中。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 334, 'prompt_tokens': 31, 'total_tokens': 365, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-CKWjW1X7Dz09FHqGVyluFBoS8gknH', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--a8877c15-b8e7-487d-b328-c5eed1943cce-0', usage_metadata={'input_tokens': 31, 'output_tokens': 334, 'total_tokens': 365, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}), AIMessage(content='大模型技术是指在机器学习和人工智能领域中，使用大规模深度学习模型进行训练和推理的一种方法。这类模型通常具有数以亿计甚至数千亿计的参数，通过大量的数据进行训练，从而能够理解和生成复杂的自然语言、图像、音频等信息。\\n\\n### 主要特点：\\n\\n1. **规模庞大**：大模型通常包含大量的参数，例如GPT-3有1750亿个参数。这使得模型在学习和捕捉数据中的复杂模式方面具备强大的能力。\\n\\n2. **预训练与微调**：大模型通常采用预训练-微调的策略。先在大规模数据集上进行无监督的预训练，然后在特定任务上进行微调，从而实现较好的性能。\\n\\n3. **多功能性**：大模型可以被应用于多种任务，例如文本生成、翻译、问答、图像识别等，具有较高的通用性。\\n\\n4. **计算资源需求高**：训练这样的大模型需要强大的计算资源，通常需要使用高效的GPU集群或TPU。\\n\\n### 应用场景：\\n\\n- **自然语言处理**：如对话系统、文本生成、情感分析等。\\n- **计算机视觉**：如图像分类、目标检测、图像生成等。\\n- **推荐系统**：通过分析用户行为数据来提供个性化推荐。\\n\\n### 挑战与前景：\\n\\n尽管大模型技术展现了许多优势，但也面临一些挑战，如：\\n\\n- **计算成本**：训练和推理的计算资源需求较高。\\n- **数据依赖**：模型性能依赖于训练数据的质量和多样性。\\n- **可解释性**：大模型的决策过程往往难以理解。\\n- **道德与隐私问题**：使用时需要关注数据隐私和潜在的偏见问题。\\n\\n未来，大模型技术有望在多个领域持续发展，推动更智能的应用与服务，同时研究者也在努力解决其带来的挑战。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 450, 'prompt_tokens': 31, 'total_tokens': 481, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-CKWjWjOOk89q4sS2I15n4ZWsg35Ho', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--fb33f309-cdac-48b4-a8d2-2f8dc0bfaca1-0', usage_metadata={'input_tokens': 31, 'output_tokens': 450, 'total_tokens': 481, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})]\n"
     ]
    }
   ],
   "execution_count": 23
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "举例4：关于同步和异步方法的调用\n",
    "\n",
    "体会1："
   ],
   "id": "a92935b4cc1b043d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:28:24.170065Z",
     "start_time": "2025-09-27T21:28:14.138559Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import time\n",
    "\n",
    "def call_model():\n",
    "    # 模拟同步API调用\n",
    "    print(\"开始调用模型...\")\n",
    "    time.sleep(5)  # 模拟调用等待,单位：秒\n",
    "    print(\"模型调用完成。\")\n",
    "\n",
    "def perform_other_tasks():\n",
    "    # 模拟执行其他任务\n",
    "    for i in range(5):\n",
    "        print(f\"执行其他任务 {i + 1}\")\n",
    "        time.sleep(1)  # 单位：秒\n",
    "\n",
    "def main():\n",
    "    start_time = time.time()\n",
    "    call_model()\n",
    "    perform_other_tasks()\n",
    "    end_time = time.time()\n",
    "    total_time = end_time - start_time\n",
    "    return f\"总共耗时：{total_time}秒\"\n",
    "\n",
    "# 运行同步任务并打印完成时间\n",
    "main_time = main()\n",
    "print(main_time)"
   ],
   "id": "a33c2a2447d0f329",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始调用模型...\n",
      "模型调用完成。\n",
      "执行其他任务 1\n",
      "执行其他任务 2\n",
      "执行其他任务 3\n",
      "执行其他任务 4\n",
      "执行其他任务 5\n",
      "总共耗时：10.021854877471924秒\n"
     ]
    }
   ],
   "execution_count": 24
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "体会2：",
   "id": "166a56e04ee1d9f9"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-27T21:29:24.061887Z",
     "start_time": "2025-09-27T21:29:19.054562Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import asyncio\n",
    "import time\n",
    "\n",
    "async def async_call(llm):\n",
    "    await asyncio.sleep(5)  # 模拟异步操作\n",
    "    print(\"异步调用完成\")\n",
    "\n",
    "async def perform_other_tasks():\n",
    "    await asyncio.sleep(5)  # 模拟异步操作\n",
    "    print(\"其他任务完成\")\n",
    "\n",
    "async def run_async_tasks():\n",
    "    start_time = time.time()\n",
    "    await asyncio.gather(\n",
    "        async_call(None),  # 示例调用，使用None模拟LLM对象\n",
    "        perform_other_tasks()\n",
    "    )\n",
    "    end_time = time.time()\n",
    "    return f\"总共耗时：{end_time - start_time}秒\"\n",
    "\n",
    "# # 正确运行异步任务的方式\n",
    "# if __name__ == \"__main__\":\n",
    "#     # 使用 asyncio.run() 来启动异步程序\n",
    "#     result = asyncio.run(run_async_tasks())\n",
    "#     print(result)\n",
    "\n",
    "\n",
    "# 在 Jupyter 单元格中直接调用\n",
    "result = await run_async_tasks()\n",
    "print(result)"
   ],
   "id": "9172542340ec0765",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "异步调用完成\n",
      "其他任务完成\n",
      "总共耗时：5.002267122268677秒\n"
     ]
    }
   ],
   "execution_count": 25
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "",
   "id": "ad6666c3d65aafc"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
